package com.marianhello.bgloc;

import android.os.Environment;

import java.io.FileOutputStream;
import java.util.Date;

/**
 * Created by zilu on 2/22/2018.
 */

public class LogUtil {

    public static void d(String tag, String message ){
        String msg = buildLogMessage(tag, message);
        try {
            savaFileToSD("DemoLog.txt", msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String buildLogMessage(String tag, String message) {
        String date = new Date().toString();

        return date +  " ---- " + "[" + tag + "]" + " ---- " + message +"\n";
    }

    //往SD卡写入文件的方法
    private static void savaFileToSD(String filename, String filecontent) throws Exception {
        //如果手机已插入sd卡,且app具有读写sd卡的权限
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;

            //这里就不要用openFileOutput了,那个是往手机内存中写数据的
            FileOutputStream output = new FileOutputStream(filename, true );
            output.write(filecontent.getBytes());
            //将String字符串以字节流的形式写入到输出流中
            output.close();
            //关闭输出流
        }
    }

}
